<?php

/**
 * Description of Helpers_Breadcrumbs
 *
 * @author a.novikov
 */
class Helpers_Breadcrumbs extends Helpers_Base {

	public function getViewPath() {
		return 'layouts/blocks/breadcrumbs.tpl';
	}

	public function breadcrumbs($source) {

		if ($source instanceof ProductRow) {
			$breadcrumbs = $this->getProductBreadcrumbs($source);
		}
		elseif ($source instanceof ProductCategoryRow) {
			$breadcrumbs = $this->getCategoryBreadcrumbs($source->getId());
		}
		elseif ($source instanceof Showcase) {
			$breadcrumbs = $this->getShowcaseBreadcrumbs($source);
		}
		elseif ( is_string($source) ) {
			$breadcrumbs = $this->getSimpleBreadcrumbs($source);
		}
		else {
			throw new Exception('Invalid source');
		}
		
		$this->view->breadcrumbs = ContentList::factoryByClassName('List_Breadcrumb_Catalog', $breadcrumbs);

		return $this->render();
	}

	/**
	 *
	 * @param int $id
	 * @return array[int]Breadcrumb $breadcrumbs
	 */
	public function getCategoryBreadcrumbs($id) {
		$id = (int)$id;
		$rowset = Categories::getInstance()->getBreadcrumbs($id);

		$breadcrumbs = array();
		$lastRow = null;
		foreach ($rowset as $row) {
			$breadcrumbs[] = Breadcrumb::fromProductCategoryRow($row);
			$lastRow = $row;
		}
		$row = CategoryService::getInstance()->createRow();
		if ($lastRow) {
			$breadcrumbs[] = Breadcrumb::fromProductCategoryRow($row, $lastRow);
		}
		
		return $breadcrumbs;
	}

	/**
	 *
	 * @param ProductRow $row
	 * @return array[int]Breadcrumb $breadcrumbs
	 */
	public function getProductBreadcrumbs(ProductRow $row) {
		$cache = new Cache_Slot_Array('product_breadcrubs_'.$row->getId(), 1500);
		$breadcrumbs = $cache->load();
		if (empty($breadcrumbs)) {
			$tree = CategoryService::getInstance()->getBreadcrumbs($row);
			$rowset = CategoryService::getInstance()->getBreadcrumbsByTree($tree);
			$breadcrumbs = array();
			//@todo хак для принудительного вывода товаров, если категория неопубликована
			try {
				foreach ($rowset as $catRow) {
					$breadcrumbs[] = Breadcrumb::fromProductCategoryRow($catRow);
				}
			} catch (Exception $e){}
			$breadcrumbs[] = Breadcrumb::fromProductRow($row);
			$cache->save($breadcrumbs);
		}
		return $breadcrumbs;
	}

	public function getShowcaseBreadcrumbs(Showcase $showcase) {
		$breadcrumbs = $this->getCategoryBreadcrumbs( $showcase->getCategoryId() );
		$breadcrumbs[] = Breadcrumb::fromString( $showcase->getName() );

		return $breadcrumbs;
	}

	public function getSimpleBreadcrumbs($str) {
		return array(
			Breadcrumb::fromString($str)
		);
	}
}